﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Gedea.Core;
using Gedea.Core.Repositories;

namespace Gedea.Service.Services
{
    public class ConfigurationService
    {
        static string activeRoot = Credentials.primaryRoot + DateTime.Now.Year + "\\";
        //const string accessDB = "gedeadb.mdb";

        public static void Configurate()
        {
            DirectoryManagment();

            DataBaseManagment();

            //Primer usuario / Settear
            new UserService().GetCurrentUser();

            DataManagment();
        }

        private static void DataManagment()
        {
            string[] dirArray = Directory.GetDirectories(Credentials.primaryRoot);
            int currentYearFolder;

            foreach (string dir in dirArray)
            {
                string folder = dir.Split('\\').Last();

                if (int.TryParse(folder, out currentYearFolder))
                {
                    if (Credentials.currentUser.UserId != 0
                        && currentYearFolder < DateTime.Now.Year - Credentials.currentUser.RecordsDuration)
                    {
                        string[] files = Directory.GetFiles(Credentials.primaryRoot + folder);

                        foreach (string file in files)
                        {
                            File.SetAttributes(file, FileAttributes.Normal);
                            File.GetAccessControl(file);
                            File.Delete(file);
                        }
                        Directory.GetAccessControl(Credentials.primaryRoot + folder);
                        Directory.Delete(Credentials.primaryRoot + folder, true);
                    }
                }
            }
        }

        private static void DataBaseManagment()
        {
            ConfigurationRepository cr = new ConfigurationRepository();

            if(!cr.IsDataBaseCreated())
            {
                cr.CreateDatabase();
                cr.CreateTables();
            }
        }

        private static void DirectoryManagment()
        {
            if (!Directory.Exists(activeRoot))
            {
                //Directory.CreateDirectory(currentRoot, new System.Security.AccessControl.DirectorySecurity());
                Directory.CreateDirectory(activeRoot);
            }

            if (!Directory.Exists(activeRoot + Credentials.GenerationFolder))
            {
                Directory.CreateDirectory(activeRoot + Credentials.GenerationFolder);
            }

            if (!Directory.Exists(activeRoot + Credentials.UploadingFolder))
            {
                Directory.CreateDirectory(activeRoot + Credentials.UploadingFolder);
            }
        }
    }
}
